using DocumentCreationSystem.Models.AgentOps;
using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services.AI;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services.AgentOps
{
    /// <summary>
    /// AgentOps集成服务实现 - 智能规划系统与Agentic对话的联动核心
    /// </summary>
    public class AgentOpsIntegrationService : IAgentOpsIntegrationService
    {
        private readonly ILogger<AgentOpsIntegrationService> _logger;
        private readonly IAgentOpsWorkflowEngine _workflowEngine;
        private readonly IPlanningTemplateExecutor _templateExecutor;
        private readonly IAgenticDialogEnhancer _dialogEnhancer;
        private readonly IAgentOpsMonitoringService _monitoringService;
        private readonly IAutonomousPlanningService _planningService;
        private readonly IAIService _aiService;
        private readonly List<IIntegrationEventListener> _eventListeners = new();

        public AgentOpsIntegrationService(
            ILogger<AgentOpsIntegrationService> logger,
            IAgentOpsWorkflowEngine workflowEngine,
            IPlanningTemplateExecutor templateExecutor,
            IAgenticDialogEnhancer dialogEnhancer,
            IAgentOpsMonitoringService monitoringService,
            IAutonomousPlanningService planningService,
            IAIService aiService)
        {
            _logger = logger;
            _workflowEngine = workflowEngine;
            _templateExecutor = templateExecutor;
            _dialogEnhancer = dialogEnhancer;
            _monitoringService = monitoringService;
            _planningService = planningService;
            _aiService = aiService;
        }

        /// <summary>
        /// 初始化集成服务
        /// </summary>
        public async Task InitializeAsync()
        {
            try
            {
                _logger.LogInformation("正在初始化AgentOps集成服务...");

                // 注册工作流事件监听器
                _workflowEngine.RegisterEventListener(new WorkflowToDialogEventBridge(_dialogEnhancer));

                // 初始化对话增强器
                var defaultDialogContext = new DialogContext
                {
                    SessionId = "system-default",
                    State = Models.AgentOps.DialogState.Ready
                };
                await _dialogEnhancer.InitializeAsync(defaultDialogContext);

                _logger.LogInformation("AgentOps集成服务初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化AgentOps集成服务时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 启动智能规划驱动的创作流程
        /// </summary>
        public async Task<IntegratedExecutionResult> StartPlanningDrivenCreationAsync(
            string userRequest,
            string? projectId = null,
            IProgress<IntegratedProgress>? progressCallback = null)
        {
            var executionId = Guid.NewGuid().ToString();
            var result = new IntegratedExecutionResult
            {
                ExecutionId = executionId,
                Status = IntegratedExecutionStatus.Planning
            };

            try
            {
                _logger.LogInformation($"开始智能规划驱动的创作流程: {userRequest}");

                // 阶段1: 智能规划
                progressCallback?.Report(new IntegratedProgress
                {
                    ExecutionId = executionId,
                    CurrentStage = IntegratedExecutionStatus.Planning,
                    OverallProgressPercentage = 10,
                    StageProgressPercentage = 0,
                    Message = "正在进行智能规划分析..."
                });

                var planningResult = await ExecutePlanningPhaseAsync(userRequest, projectId);
                result.PlanningResult = planningResult;

                // 阶段2: 工作流创建
                progressCallback?.Report(new IntegratedProgress
                {
                    ExecutionId = executionId,
                    CurrentStage = IntegratedExecutionStatus.WorkflowCreation,
                    OverallProgressPercentage = 30,
                    StageProgressPercentage = 0,
                    Message = "正在创建可执行工作流..."
                });

                var workflow = await CreateWorkflowFromPlanningAsync(planningResult, new WorkflowCreationContext
                {
                    ProjectId = projectId,
                    Options = new WorkflowCreationOptions
                    {
                        AutoStart = true,
                        EnableMonitoring = true,
                        EnableNotifications = true
                    }
                });
                result.CreatedWorkflow = workflow;

                // 阶段3: 工作流执行
                progressCallback?.Report(new IntegratedProgress
                {
                    ExecutionId = executionId,
                    CurrentStage = IntegratedExecutionStatus.WorkflowExecution,
                    OverallProgressPercentage = 50,
                    StageProgressPercentage = 0,
                    Message = "正在执行工作流..."
                });

                var workflowProgress = new Progress<WorkflowProgress>(progress =>
                {
                    progressCallback?.Report(new IntegratedProgress
                    {
                        ExecutionId = executionId,
                        CurrentStage = IntegratedExecutionStatus.WorkflowExecution,
                        OverallProgressPercentage = 50 + (progress.ProgressPercentage / 2),
                        StageProgressPercentage = progress.ProgressPercentage,
                        Message = progress.Message,
                        Details = $"当前步骤: {progress.CurrentStep}"
                    });
                });

                var executionResult = await _workflowEngine.ExecuteWorkflowAsync(
                    workflow.Id,
                    new WorkflowExecutionContext
                    {
                        ProjectId = projectId,
                        InputParameters = new Dictionary<string, object>
                        {
                            ["UserRequest"] = userRequest,
                            ["PlanningResult"] = planningResult
                        }
                    },
                    workflowProgress);

                // 完成
                result.Status = executionResult.Status == WorkflowStatus.Completed
                    ? IntegratedExecutionStatus.Completed
                    : IntegratedExecutionStatus.Failed;
                result.EndTime = DateTime.Now;

                progressCallback?.Report(new IntegratedProgress
                {
                    ExecutionId = executionId,
                    CurrentStage = result.Status,
                    OverallProgressPercentage = 100,
                    StageProgressPercentage = 100,
                    Message = result.Status == IntegratedExecutionStatus.Completed
                        ? "创作流程已完成"
                        : "创作流程执行失败"
                });

                // 通知事件监听器
                foreach (var listener in _eventListeners)
                {
                    await listener.OnWorkflowCreatedAsync(workflow.Id, planningResult);
                }

                _logger.LogInformation($"智能规划驱动的创作流程完成: {result.Status}");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行智能规划驱动的创作流程时发生错误");
                result.Status = IntegratedExecutionStatus.Failed;
                result.EndTime = DateTime.Now;
                result.Errors.Add(ex.Message);

                foreach (var listener in _eventListeners)
                {
                    await listener.OnIntegrationErrorAsync("StartPlanningDrivenCreation", ex);
                }

                return result;
            }
        }

        /// <summary>
        /// 从智能规划结果创建工作流
        /// </summary>
        public async Task<AgentWorkflow> CreateWorkflowFromPlanningAsync(
            PlanningResult planningResult,
            WorkflowCreationContext context)
        {
            try
            {
                _logger.LogInformation($"从规划结果创建工作流: {planningResult.Id}");

                // 创建规划模板
                var template = await ConvertPlanningResultToTemplateAsync(planningResult);

                // 验证模板
                var validationResult = await _templateExecutor.ValidateTemplateAsync(template);
                if (!validationResult.IsValid)
                {
                    throw new InvalidOperationException($"模板验证失败: {string.Join(", ", validationResult.Errors)}");
                }

                // 优化模板
                var optimizedTemplate = await _templateExecutor.OptimizeTemplateAsync(template, new TemplateOptimizationOptions
                {
                    OptimizeForPerformance = true,
                    OptimizeForQuality = true,
                    EnableParallelization = context.Options.EnableMonitoring
                });

                // 创建可执行工作流
                var workflow = await _templateExecutor.CreateExecutableWorkflowAsync(optimizedTemplate, context);

                // 设置工作流属性
                workflow.SourceTemplateId = template.Id;
                workflow.ProjectId = context.ProjectId;
                workflow.CreatedBy = context.UserId;
                workflow.Priority = context.Options.Priority;

                _logger.LogInformation($"工作流创建成功: {workflow.Id}");
                return workflow;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "从规划结果创建工作流时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 同步工作流状态到对话窗口
        /// </summary>
        public async Task SyncWorkflowStatusToDialogAsync(string workflowId, string dialogSessionId)
        {
            try
            {
                var workflowStatus = await _workflowEngine.GetWorkflowStatusAsync(workflowId);
                var workflowMetrics = await _workflowEngine.GetWorkflowMetricsAsync(workflowId);

                // 创建状态更新消息
                var statusUpdate = new WorkflowStatusUpdate
                {
                    WorkflowId = workflowId,
                    WorkflowName = workflowStatus.Name,
                    NewStatus = workflowStatus.Status,
                    ProgressPercentage = CalculateProgressPercentage(workflowStatus),
                    Message = GenerateStatusMessage(workflowStatus, workflowMetrics)
                };

                // 通知对话增强器
                var dialogContext = new DialogContext
                {
                    SessionId = dialogSessionId,
                    ActiveWorkflows = { workflowId }
                };

                // 这里可以通过事件系统或直接调用来更新对话界面
                // 具体实现取决于对话系统的架构

                foreach (var listener in _eventListeners)
                {
                    await listener.OnWorkflowStatusSyncedAsync(workflowId, dialogSessionId, workflowStatus.Status);
                }

                _logger.LogDebug($"工作流状态已同步到对话窗口: {workflowId} -> {dialogSessionId}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"同步工作流状态到对话窗口时发生错误: {workflowId}");
                throw;
            }
        }

        /// <summary>
        /// 从对话窗口控制工作流
        /// </summary>
        public async Task<WorkflowControlResult> ControlWorkflowFromDialogAsync(
            string workflowId,
            WorkflowControlCommand command,
            Dictionary<string, object>? parameters = null)
        {
            try
            {
                _logger.LogInformation($"从对话窗口控制工作流: {workflowId}, 命令: {command}");

                var result = new WorkflowControlResult();

                switch (command)
                {
                    case WorkflowControlCommand.Start:
                        // 这里需要实现启动逻辑
                        result.Success = true;
                        result.Message = "工作流已启动";
                        result.NewStatus = WorkflowStatus.Running;
                        break;

                    case WorkflowControlCommand.Pause:
                        await _workflowEngine.PauseWorkflowAsync(workflowId);
                        result.Success = true;
                        result.Message = "工作流已暂停";
                        result.NewStatus = WorkflowStatus.Paused;
                        break;

                    case WorkflowControlCommand.Resume:
                        await _workflowEngine.ResumeWorkflowAsync(workflowId);
                        result.Success = true;
                        result.Message = "工作流已恢复";
                        result.NewStatus = WorkflowStatus.Running;
                        break;

                    case WorkflowControlCommand.Stop:
                        await _workflowEngine.StopWorkflowAsync(workflowId);
                        result.Success = true;
                        result.Message = "工作流已停止";
                        result.NewStatus = WorkflowStatus.Cancelled;
                        break;

                    default:
                        result.Success = false;
                        result.Message = $"不支持的命令: {command}";
                        break;
                }

                _logger.LogInformation($"工作流控制完成: {workflowId}, 结果: {result.Success}");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"从对话窗口控制工作流时发生错误: {workflowId}");
                return new WorkflowControlResult
                {
                    Success = false,
                    Message = $"控制失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取集成状态概览
        /// </summary>
        public async Task<IntegrationStatusOverview> GetIntegrationStatusAsync()
        {
            try
            {
                var activeWorkflows = await _workflowEngine.GetActiveWorkflowsAsync();
                var systemHealth = await _monitoringService.GetSystemHealthAsync();
                var dashboardData = await _monitoringService.GetDashboardDataAsync();

                return new IntegrationStatusOverview
                {
                    TotalActiveWorkflows = activeWorkflows.Count,
                    SystemHealth = systemHealth.OverallHealth,
                    LastUpdated = DateTime.Now,
                    PerformanceMetrics = dashboardData.Performance,
                    RecentActivities = dashboardData.RecentActivities.Take(10).ToList()
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取集成状态概览时发生错误");
                throw;
            }
        }

        // 私有辅助方法
        private async Task<PlanningResult> ExecutePlanningPhaseAsync(string userRequest, string? projectId)
        {
            // 调用现有的智能规划服务
            var preferredRoot = GetPreferredProjectRootPath();
            var planningResult = await _planningService.PlanAndExecuteAsync(userRequest, projectId, null, preferredRoot);

            // 转换为新的PlanningResult格式
            return new PlanningResult
            {
                UserRequest = userRequest,
                Type = DeterminePlanningType(planningResult),
                CreatedAt = DateTime.Now,
                Metadata = new PlanningMetadata
                {
                    ExecutionTimeMs = (long)(planningResult.MonitoringResult?.PerformanceMetrics?.ExecutionTime.TotalMilliseconds ?? 0),
                    QualityScore = planningResult.MonitoringResult?.QualityMetrics?.ContentQuality ?? 0,
                    ConfidenceScore = (planningResult.ExecutionResult?.Plan?.UserIntent?.ComplexIntent as DocumentCreationSystem.Services.ComplexIntent)?.Confidence ?? 0
                }
            };
        }

        private async Task<PlanningTemplate> ConvertPlanningResultToTemplateAsync(PlanningResult planningResult)
        {
            // 这里实现将规划结果转换为模板的逻辑
            // 具体实现需要根据规划结果的结构来定制
            return new PlanningTemplate
            {
                Name = $"规划模板_{planningResult.Id}",
                Description = $"基于用户请求生成的规划模板: {planningResult.UserRequest}",
                Type = TemplateType.Hybrid,
                Content = new TemplateContent
                {
                    RawContent = planningResult.UserRequest
                }
            };
        }

        private PlanningType DeterminePlanningType(AutonomousPlanResult planningResult)
        {
            // 根据规划结果确定类型
            var plan = planningResult.ExecutionResult?.Plan;
            if (plan?.CharacterPlan != null && plan?.WorkflowPlan != null)
                return PlanningType.Comprehensive;
            else if (plan?.CharacterPlan != null)
                return PlanningType.CharacterOnly;
            else if (plan?.WorkflowPlan != null)
                return PlanningType.WorkflowOnly;
            else
                return PlanningType.Custom;
        }

        private int CalculateProgressPercentage(WorkflowStatusInfo workflowStatus)
        {
            // 根据工作流状态计算进度百分比
            return workflowStatus.Status switch
            {
                Models.AgentOps.WorkflowStatus.Created => 0,
                Models.AgentOps.WorkflowStatus.Pending => 5,
                Models.AgentOps.WorkflowStatus.Running => workflowStatus.Progress, // 基于实际进度
                Models.AgentOps.WorkflowStatus.Paused => workflowStatus.Progress,
                Models.AgentOps.WorkflowStatus.Completed => 100,
                Models.AgentOps.WorkflowStatus.Failed => 0,
                Models.AgentOps.WorkflowStatus.Cancelled => 0,
                _ => 0
            };
        }

        private string GenerateStatusMessage(WorkflowStatusInfo workflowStatus, WorkflowMetrics metrics)
        {
            return workflowStatus.Status switch
            {
                Models.AgentOps.WorkflowStatus.Running => $"正在执行中... 已运行 {metrics.ExecutionTime:mm\\:ss}",
                Models.AgentOps.WorkflowStatus.Completed => $"执行完成，总用时 {metrics.ExecutionTime:mm\\:ss}",
                Models.AgentOps.WorkflowStatus.Failed => "执行失败",
                Models.AgentOps.WorkflowStatus.Paused => "已暂停",
                _ => workflowStatus.Status.ToString()
            };
        }

        public Task RegisterWorkflowEventsToDialogAsync(string workflowId, string dialogSessionId)
        {
            throw new NotImplementedException();
        }

        public Task<List<SmartSuggestion>> GenerateSmartSuggestionsAsync(IntegrationContext context)
        {
            throw new NotImplementedException();
        }

        private string? GetPreferredProjectRootPath()
        {
            try
            {
                // 从主窗口获取当前项目根路径
                if (System.Windows.Application.Current?.MainWindow is DocumentCreationSystem.MainWindow main)
                {
                    var path = main.DocumentEditorControl?.CurrentProjectPath;
                    if (!string.IsNullOrWhiteSpace(path)) return path;
                }
            }
            catch { }
            return null;
        }

        public Task<SmartDecisionResult> ExecuteSmartDecisionAsync(SmartDecisionRequest decisionRequest)
        {
            throw new NotImplementedException();
        }

        public Task<MonitoringData> GetRealTimeMonitoringDataAsync(MonitoringScope scope)
        {
            throw new NotImplementedException();
        }

        public void RegisterEventListener(IIntegrationEventListener listener)
        {
            _eventListeners.Add(listener);
        }

        public void RemoveEventListener(IIntegrationEventListener listener)
        {
            _eventListeners.Remove(listener);
        }
    }

    /// <summary>
    /// 工作流到对话的事件桥接器
    /// </summary>
    internal class WorkflowToDialogEventBridge : IWorkflowEventListener
    {
        private readonly IAgenticDialogEnhancer _dialogEnhancer;

        public WorkflowToDialogEventBridge(IAgenticDialogEnhancer dialogEnhancer)
        {
            _dialogEnhancer = dialogEnhancer;
        }

        public async Task OnWorkflowStatusChangedAsync(string workflowId, Models.AgentOps.WorkflowStatus oldStatus, Models.AgentOps.WorkflowStatus newStatus)
        {
            // 将工作流状态变化通知到对话系统
            // 具体实现取决于对话系统的架构
            await Task.CompletedTask;
        }

        public async Task OnTaskCompletedAsync(string workflowId, string taskId, Models.AgentOps.TaskExecutionResult result)
        {
            // 任务完成通知
            await Task.CompletedTask;
        }

        public async Task OnWorkflowErrorAsync(string workflowId, WorkflowError error)
        {
            // 工作流错误通知
            await Task.CompletedTask;
        }

        public async Task OnWorkflowCompletedAsync(string workflowId, Models.AgentOps.WorkflowExecutionResult result)
        {
            // 工作流完成通知
            await Task.CompletedTask;
        }
    }
}
